<template>
	<div
		class="admin-tab__button-tab"
		:class="{ 'admin-tab__button-tab--unclosable': !closable }"
		:style="buttonStyle"
		@mouseenter="setTrue"
		@mouseleave="setFalse"
	>
		<span class="admin-tab__button-tab__preffix">
			<slot></slot>
		</span>
		<div v-if="closable" class="admin-tab__button-tab__icon">
			<icon-close :is-active="isIconActive" :active-color="primaryColor" @click="handleClose" />
		</div>
	</div>
</template>

<script setup lang="ts" name="ButtonTab">
import { computed } from 'vue'
import IconClose from '../../ChromeTabs/components/IconClose.vue'
import { useBoolean } from '@/hooks/useBoolean'
import { addColorAlpha } from '@/utils/color'
import { THEME_CONFIG } from '@/config/config'

interface Props {
	/** 暗黑模式 */
	darkMode?: boolean
	/** 激活状态 */
	isActive?: boolean
	/** 主题颜色 */
	primaryColor?: string
	/** 边框颜色 */
	borderColor?: string
	/** 暗黑模式的边框颜色 */
	darkBorderColor?: string
	/** 是否显示关闭图标 */
	closable?: boolean
}

const props = withDefaults(defineProps<Props>(), {
	darkMode: false,
	isActive: false,
	primaryColor: THEME_CONFIG.primary,
	borderColor: '#e5e7eb',
	darkBorderColor: '#ffffff3d',
	closable: true
})

interface Emits {
	/** 点击关闭图标 */
	(e: 'close'): void
}

const emit = defineEmits<Emits>()

const { bool: isHover, setTrue, setFalse } = useBoolean()

const isIconActive = computed(() => props.isActive || isHover.value)

const buttonStyle = computed(() => {
	const style: Record<string, string> = {}
	style.borderColor = props.darkMode ? props.darkBorderColor : props.borderColor
	if (isIconActive.value) {
		style.color = props.primaryColor
		style.borderColor = addColorAlpha(props.primaryColor, 0.3)
		if (props.isActive) {
			const alpha = props.darkMode ? 0.15 : 0.1
			style.backgroundColor = addColorAlpha(props.primaryColor, alpha)
		}
	}
	return style
})

function handleClose(e: MouseEvent) {
	e.stopPropagation()
	emit('close')
}
</script>
<style lang="scss" scoped>
.admin-tab__button-tab {
	position: relative;
	display: inline-flex;
	align-items: center;
	justify-content: center;
	height: 28px;
	padding-right: 6px;
	padding-left: 14px;
	font-size: var(--el-font-size-base);
	cursor: pointer;
	border-style: solid;
	border-width: 1px;
	border-radius: 2px;
	&:not(:last-child) {
		margin-right: 10px;
	}
	&--unclosable {
		padding-right: 14px !important;
	}
	&__preffix {
		white-space: nowrap;
	}
	&__icon {
		padding-left: 10px;
	}
}
</style>
